package sh.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class DownloadImage {
	public static void main(String args[]){
		  try {

			    GetImg gi=new GetImg();
			    gi.blobRead("c:/1.jpg", 1);
			   } catch (Exception e) {
				   e.printStackTrace();
			    //System.out.println("[Main func error: ]" + e.getMessage());
			   }		
	}
}
class GetImg {

	//private static final String URL = "jdbc:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=UTF-8";

	private Connection conn = null; 
	private PreparedStatement pstmt = null; 
	private ResultSet rs = null; 
	private File file = null;


	public void blobRead(String outfile, int picID) throws Exception {
	   FileOutputStream fos = null;
	   InputStream is = null;
	   byte[] Buffer = new byte[4096];

	   try {
	   /* Class.forName("org.gjt.mm.mysql.Driver").newInstance();
	    conn = DriverManager.getConnection(URL);*/
		   
		   new oracle.jdbc.driver.OracleDriver();
			String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
			Connection conn = DriverManager.getConnection(url, "liuchao", "liuchao");
		   
	    //pstmt = conn.prepareStatement("select image from t_image where id=?");
			String sql = "select image from t_image where id=1";
			pstmt = conn.prepareStatement(sql);
			//test:  select image from t_image where id=1;
	   // pstmt.setInt(1, picID); // 传入要取的图片的ID
	    rs = pstmt.executeQuery();
	    rs.next();

	    file = new File(outfile);
	    if (!file.exists()) {
	     file.createNewFile(); // 如果文件不存在，则创建
	    }
	    fos = new FileOutputStream(file);
	   is = rs.getBinaryStream("image");
	    int size = 0;
	   
	    while ((size = is.read(Buffer)) != -1) {
	     // System.out.println(size);
	     fos.write(Buffer, 0, size);
	    }

	   } catch (Exception e) {
	    System.out.println( e.getMessage());
	   } finally {
	    // 关闭用到的资源
	    fos.close();
	    rs.close();
	    pstmt.close();
	    if(conn != null){
	    	conn.close();
	    }
	   }
	}
}
